#ifndef IMAGEMAPPINGMANAGER_H
#define IMAGEMAPPINGMANAGER_H
#include "../models/ImageCoordinate.h"

class ImageMappingManager : public QObject
{
    Q_OBJECT

public:
    explicit ImageMappingManager(QObject *parent = nullptr);

    // 参数设置
    void setParameters(int fovRows, int fovCols, int fixtureRows, int fixtureCols);
    void getParameters(int &fovRows, int &fovCols, int &fixtureRows, int &fixtureCols) const;

    // 核心功能
    bool scanImageFolder(const QString& folderPath);
    bool calculateCoordinates();
    bool saveMappingToConfig(const QString& configPath);
    bool loadMappingFromConfig(const QString& configPath);

    // 图像重命名功能
    bool renameImagesForHalcon(const QString& outputFolder = "");
    QString generateHalconCompatibleName(const QString& originalName, const ImageCoordinate& coord) const;
    void setRenamingPattern(const QString& pattern) { m_renamingPattern = pattern; }

    // 数据获取 - 供其他控件使用
    int getTotalImageCount() const { return m_imageInfoMap.size(); }
    int getCalculatedTotalImages() const;
    QString getCurrentFolder() const { return m_currentFolder; }

    // 多种方式获取映射数据
    QMap<QString, ImageCoordinate> getImageCoordinateMap() const;
    QMap<QString, ImageFileInfo> getImageInfoMap() const { return m_imageInfoMap; }
    QList<ImageFileInfo> getImageInfoList() const { return m_imageInfoMap.values(); }
    QStringList getOriginalImageFiles() const;
    QStringList getRenamedImageFiles() const;

    ImageCoordinate getImageCoordinate(const QString& fileName) const;
    ImageFileInfo getImageInfo(const QString& fileName) const;
    QString getRenamedPath(const QString& originalFileName) const;

    // 验证和状态
    bool validateParameters() const;
    bool isMappingValid() const;
    QString getStatusMessage() const;

    // 临时文件夹管理
    void setTempFolder(const QString& folder) { m_tempFolder = folder; }
    QString getTempFolder() const { return m_tempFolder; }
    void cleanupTempFolder();

signals:
    void mappingUpdated();
    void scanCompleted(bool success, const QString& message);
    void parametersChanged();
    void imagesRenamed(bool success, const QString& message);

private:
    QStringList getImageFilesFromFolder(const QString& folderPath);
    QString sanitizeFileName(const QString& fileName) const;

    // 参数
    int m_fovRows;
    int m_fovCols;
    int m_fixtureRows;
    int m_fixtureCols;
    QString m_renamingPattern;

    // 数据
    QMap<QString, ImageFileInfo> m_imageInfoMap;  // 原始文件名 -> 文件信息
    QString m_currentFolder;
    QString m_tempFolder;

    QStringList m_imageNameList;
};


#endif // IMAGEMAPPINGMANAGER_H
